import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as chroma from 'chroma-js'
import type { GeoJSON } from 'leaflet'

interface CountyFeature {
  properties: {
    name: string
    adcode: string
    center: string
  }
}

export const useMapStore = defineStore('map', {
  state: () => ({
    geoJsonData: null as GeoJSON | null,
    selectedCounty: null as CountyFeature | null
  }),
  actions: {
    async loadGeoJsonData() {
        try {
          // 确保使用正确的相对路径
          const response = await fetch('/src/assets/geojson/hubei.json')
          if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`)
          
          // 验证内容类型
          const contentType = response.headers.get('content-type')
          if (!contentType?.includes('application/json')) {
            const text = await response.text()
            throw new Error(`Expected JSON but got: ${text.substring(0, 100)}...`)
          }
          
          this.geoJsonData = await response.json()
        } catch (error) {
          console.error('加载GeoJSON数据失败:', error)
          // 提供备用数据或错误处理
          this.geoJsonData = { type: 'FeatureCollection', features: [] }
        }
      },
    areaStyle(feature: CountyFeature) {
      // 根据县级编码生成颜色
      const colorScale = chroma.scale(['#f7fbff', '#08306b'])
      return {
        fillColor: colorScale(Number(feature.properties.adcode) % 10 / 10).hex(),
        weight: 1,
        opacity: 1,
        color: 'white',
        fillOpacity: 0.7
      }
    },
    onEachFeature(feature: CountyFeature, layer: any) {
      layer.bindPopup(`
        <h3>${feature.properties.name}</h3>
        <p>行政区划码: ${feature.properties.adcode}</p>
      `)
      
      layer.on({
        click: () => {
          this.selectedCounty = feature
        }
      })
    }
  }
})